// 升序排序
import sortBy from 'lodash/sortBy'

const initState = {
  channels: [],
  articles: {},
  restChannels: [],
  // 频道高亮索引
  channelActiveIndex: 0,
}
const home = (state = initState, action) => {
  switch (action.type) {
    case 'home/getMyChannels':
      return {
        ...state,
        channels: action.payload,
      }
    case 'home/getRestChannels':
      return { 
        ...state,
        restChannels: action.payload,
      }
    case 'home/addChannel':
      const deletedChannel = state.restChannels.find(item => item.id === action.payload)
      return {
        ...state,
        restChannels: state.restChannels.filter(item => item.id !== action.payload),
        channels: [...state.channels, deletedChannel],
        // channels: [...state.channels,  action.payload.id],
      }
    case 'home/deleteChannel':
      return {
        ...state,
        channels: state.channels.filter(item => item.id !== action.payload.id),
        restChannels: sortBy([...state.restChannels, action.payload], 'id'),
      }
    case 'home/selectTab':
      return {
        ...state,
        channelActiveIndex: action.payload,
      }
    case 'home/getArticles':
      // console.log(state);
      return {
        ...state,
        articles: {
          ...state.articles,
          [action.payload.channelId]: {
            prevTime: action.payload.prevTime,
            list: action.payload.list
          }
        }
      }
      case 'home/getMoreArticles':
        // 数据键
        const channelId =action.payload.channelId
        // 更新加载前的当前频道列表数据
        const oldList=state.articles[channelId].list
        // console.log(befoList);
        return{
          ...state,
          articles: {
            ...state.articles,
            [channelId]: {
              prevTime: action.payload.prevTime,
              list: [...oldList,...action.payload.list]
            }
          }
        }
    default:
      return state
  }
}

export { home }
